import logging
from logging.handlers import RotatingFileHandler
from flask import Flask, render_template
from flask import g
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import CSRFProtect, csrf
from redis import StrictRedis
from flask_session import Session
from config import configs



from werkzeug.routing import BaseConverter


def set_up(level):
    # 设置日志的记录等级
    logging.basicConfig(level=level)  # 调试debug级
    # 创建日志记录器，指明日志保存的路径、每个日志文件的最大大小、保存的日志文件个数上限
    file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024 * 1024 * 100, backupCount=10)
    # 创建日志记录的格式                 日志等级    输入日志信息的文件名 行数    日志信息
    formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')
    # 为刚创建的日志记录器设置日志记录格式
    file_log_handler.setFormatter(formatter)
    # 为全局的日志工具对象（flask app使用的）添加日志记录器
    logging.getLogger().addHandler(file_log_handler)


db = SQLAlchemy()
src = None

def create_app(config_name):
    set_up(configs[config_name].LEVEL_LOG)
    app = Flask(__name__)
    app.config.from_object(configs[config_name])
    # 将自定义的过滤器函数，转成模板中可以使用的过滤器
    from first_info.utils import comment
    app.add_template_filter(comment.do_rank, "rank")
    # db = SQLAlchemy(app)
    db.init_app(app)
    global src
    src = StrictRedis(host=configs[config_name].REDIS_HOST, port=configs[config_name].REDIS_PORT, decode_responses=True)
    CSRFProtect(app)

    # 将session写入redis服务器，设置type = redis
    Session(app)
    # 在请求之后拿到response进行设置cookie
    @app.after_request
    def after_request(response):
        # 通过generate_csrf()可以获取到一个csrf_token值
        csrf_token = csrf.generate_csrf()
        response.set_cookie("csrf_token", csrf_token)
        return response

    # 捕获404界面
    from first_info.utils.comment import user_login_data
    @app.errorhandler(404)
    # @app.route('/4')
    @user_login_data
    def page_not_found():
        user = g.user
        data = {
            'user': user.to_dict() if user else None
        }
        return render_template('news/404.html', **data)

    from first_info.modules.index import index_blue
    app.register_blueprint(index_blue)
    from first_info.modules.passport import passport_blue
    app.register_blueprint(passport_blue)
    from first_info.modules.news import news_blue
    app.register_blueprint(news_blue)
    from first_info.modules.user import user_blue
    app.register_blueprint(user_blue)
    from first_info.modules.admin import admin_blue
    app.register_blueprint(admin_blue)
    return app

